package cn.sytton.taffecloud.common.db.datasource;

import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.VendorDatabaseIdProvider;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * 数据源配置工具类
 *
 * @author skyrock
 */
public class DataSourcePropertiesBuilder {

    //提取出DataSourceBiz DataSourceLog 中的公共方法
    public static DatabaseIdProvider newDatabaseIdProvider() {
        DatabaseIdProvider databaseIdProvider = new VendorDatabaseIdProvider();
        Properties p = new Properties();
        p.setProperty("MariaDB", "mysql");
        p.setProperty("Oracle", "oracle");
        p.setProperty("MySQL", "mysql");
        p.setProperty("SQL Server", "sqlserver");
        p.setProperty("DB2", "db2");
        databaseIdProvider.setProperties(p);
        return databaseIdProvider;
    }

    //提取出DataSourceMaster DataSourceLog 中的公共方法
    public static SqlSessionFactory newSqlSessionFactory(DataSource dataSource,
                                                         DatabaseIdProvider databaseIdProvider,
                                                         String xmlPath) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setDatabaseIdProvider(databaseIdProvider);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(xmlPath));
        return bean.getObject();
    }
}
